﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using Gma.UserActivityMonitor;

namespace MercuryFE
{
    public partial class KeyCode : Form
    {
        public string KeycodePressed = "";

        private Inputs _inputs = null;
        private Timer _timer = null;
        private int _counter;


        public KeyCode(InputDeviceType deviceType)
        {
            InitializeComponent();
            _counter = 0;
            _timer = new Timer();

            bool checkMouse = false, checkKey = false, checkJoy = false;

            if (deviceType == InputDeviceType.keyboard)
                checkKey = true;
            else if (deviceType == InputDeviceType.joystick)
                checkJoy = true;
            else if (deviceType == InputDeviceType.mouse)
                checkMouse = true;

            _inputs = new Inputs(this.Handle, checkKey, checkMouse, checkJoy); 

            _timer.Tick += new EventHandler(_timer_Tick);
            _timer.Interval = 16; // every 16 ms

            _timer.Start();

        }

        void _timer_Tick(object sender, EventArgs e)
        {
            // poll the devices, and if we find something has been triggered, store it in the raw value - so we can process it accordingly
            List<InputDeviceState> states =  _inputs.pollDevices(true);

            foreach (InputDeviceState ids in states)
            {
                if (!string.IsNullOrEmpty(ids.RawValue))
                {
                    this.KeycodePressed  = ids.RawValue;
                    cleanup();
                }
                
            }
            // check if we have gone over 10 seconds (10,000 ms / 16)
            if (_counter++ > 625)
            {
                this.KeycodePressed = null;
                cleanup();

            }
        }

        private void cleanup()
        {
            _timer.Stop();
            _timer.Dispose();

            _inputs.releaseDevices();
            _inputs = null;
            this.Close();
        }


    }
}
